import { Navigate, useLocation, useRoutes } from "react-router-dom";
import { AppstoreOutlined } from "@ant-design/icons";
import { lazy, Suspense, useEffect } from "react";
import { Spin } from "antd";
import nprogress from "nprogress";

const Layout = lazy(() => import("@/layouts"));
const User = lazy(() => import("@/views/user"));
const Goods = lazy(() => import("@/views/goods"));
const Login = lazy(() => import("@/views/login"));
const Ship = lazy(() => import("@/views/ship"));
const Order = lazy(() => import("@/views/order"));
const Cargo = lazy(() => import("@/views/cargo"));
const Log = lazy(() => import("@/views/log"));
const Truck = lazy(() => import("@/views/truck"));
const NoFoundPage = lazy(() => import("@/views/noFoundPage"));

const lazyRoutes = (element) => {
    return <Suspense fallback={<Spin className="global-spin"></Spin>}>{element} </Suspense>;
};

export const menuRoute = () => [
    {
        path: "system",
        title: "系统功能",
        icon: <AppstoreOutlined />,
        element: lazyRoutes(<Layout />),
        children: [
            {
                path: "user",
                title: "用户管理",
                element: lazyRoutes(<User />),
            },
            {
                path: "goods",
                title: "货物管理",
                element: lazyRoutes(<Goods />),
            },
            {
                path: "ship",
                title: "轮船管理",
                element: lazyRoutes(<Ship />),
            },
            {
                path: "order",
                title: "订单管理",
                element: lazyRoutes(<Order />),
            },
            {
                path: "cargo",
                title: "装车管理",
                element: lazyRoutes(<Cargo />),
            },
            {
                path: "log",
                title: "日志查询",
                element: lazyRoutes(<Log />),
            },
            {
                path: "truck",
                title: "装车作业单查询",
                element: lazyRoutes(<Truck />),
            },
        ],
    },
];

const newRoutes = [
    {
        path: "/",
        element: <Navigate to="/login" replace />,
    },
    {
        path: "/",
        children: menuRoute(),
        action: () => {
            return false;
        },
    },
    {
        path: "/login",
        element: lazyRoutes(<Login />),
    },
    {
        path: "*",
        element: lazyRoutes(<NoFoundPage />),
    },
];

function Router() {
    const location = useLocation();

    // 顶部进度条
    useEffect(() => {
        nprogress.start();
    }, []);

    useEffect(() => {
        nprogress.done();

        return () => {
            nprogress.start();
        };
    }, [location]);

    return <>{useRoutes(newRoutes)}</>;
}

export default Router;
